from java.awt import BorderLayout
from java.awt.event import ActionListener
from javax.jms import MessageListener
from javax.swing import JScrollPane, JTabbedPane, JTextField
from org.memesis.pandorasbook.ui import PandoraTextPane

class ThinkNet(object):
    class SendText(ActionListener):
        def __init__(self, app):
            self.app = app
            
        def actionPerformed(self, act):
            idx = self.app.thinkNetPanes.getSelectedIndex()
            if(idx > -1):
                channel = self.app.thinkNetPanes.getTitleAt(idx)
                strr = "th %s=%s" % (channel, self.app.input.getText())
                mq.publish(applet.getProperty("thinknet-input-queue"), strr)
                self.app.input.setText("")
            
    class GetText(MessageListener):
        def __init__(self, app):
            self.app = app
            
        def onMessage(self, m):
            t = m.text
            channel, text = t.split(';;',1)
            ind = self.app.thinkNetPanes.indexOfTab(channel)
            if ind == -1:
                self.app.outputs[channel] = PandoraTextPane()
                self.app.outputs[channel].setEditable(False)
                scrolly = JScrollPane(self.app.outputs[channel])
                scrolly.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
                self.app.thinkNetPanes.addTab(channel,scrolly)
            doc = self.app.outputs[channel].getStyledDocument()
            doc.insertString(doc.getLength(),text,None)
            doc.insertString(doc.getLength(),"\n",None)
            if self.app.input.getText() == "":
                self.app.thinkNetPanes.setSelectedIndex(self.app.thinkNetPanes.indexOfTab(channel))
    
    def initGui(self, frame):
        self.frame = frame
        frame.setTitle("ThinkNet")
        
        self.thinkNetPanes = JTabbedPane()
        self.thinkNetPanes.setTabPlacement(JTabbedPane.BOTTOM)
        
        self.input = JTextField()
        self.inputListener = ThinkNet.SendText(self)
        self.input.addActionListener(self.inputListener)
        
        self.frame.getContentPane().add(self.thinkNetPanes, BorderLayout.CENTER)
        self.frame.getContentPane().add(self.input, BorderLayout.PAGE_END)
        
        self.frame.pack()
        self.frame.setSize(320, 400)
       
    
    def __init__(self, frame):
        
        self.initGui(frame)
                
        self.outputs = {}
        
        self.messageListener = ThinkNet.GetText(self)
        mq.subscribe(applet.getProperty("thinknet-output-queue"), self.messageListener)

c = ThinkNet(frame)